/*
 * @Author: i@douxuefeng.cn
 * @Date: 2023-04-15 09:18:31
 * @LastEditTime: 2023-04-15 09:20:44
 * @LastEditors: i@douxuefeng.cn
 * @Description:
 * @FilePath: /nodes/Volumes/Data/jobs/go-utils/DB/sqlite.go
 */
package DB

import (
	"time"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

type SqliteOpt struct {
	SqlFile                           string
	MaxIdle                           int
	MaxOpen                           int
	LogMode                           logger.LogLevel
	Models                            []any
	DisableForeignKeyCheckWhenMigrate bool
	EnableMigrate                     bool
}

func InitSqlite(opt *SqliteOpt) error {
	var err error
	db, err = gorm.Open(sqlite.Open(opt.SqlFile), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: opt.DisableForeignKeyCheckWhenMigrate,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: logger.Default.LogMode(opt.LogMode),
		NowFunc: func() time.Time {
			return time.Now().Truncate(time.Millisecond)
		},
	})
	if err != nil {
		return err
	}
	if opt.EnableMigrate {
		if err := db.AutoMigrate(opt.Models...); err != nil {
			return err
		}
	}
	//连接池设置
	if sqlDb, err = db.DB(); err != nil {
		return err
	} else {
		sqlDb.SetConnMaxIdleTime(time.Hour)
		sqlDb.SetMaxIdleConns(opt.MaxIdle)
		sqlDb.SetMaxOpenConns(opt.MaxOpen)
	}
	return nil
}
